<template>
  <view class="chat-container">
    <image 
      class="background-image" 
      src="/static/images/chat-backgrounds/微信图片_20250917164430.jpg"
      mode="aspectFill"
    />
    <!-- 聊天头部 -->
    <view class="chat-header">
      <view class="chat-header-left" @tap="goBack">
        <uni-icons type="arrowleft" size="24" color="#333"></uni-icons>
      </view>
      <view class="chat-header-middle">
        <image :src="chatPartner?.avatar || '/static/images/default-avatar.png'" class="chat-avatar"></image>
        <text class="chat-username">{{ chatPartner?.nickname || '对方' }}</text>
        <text v-if="chatPartner?.online" class="chat-status">在线</text>
      </view>
      <view class="chat-header-right">
        <uni-icons type="search" size="24" color="#333" @click="toggleSearch" style="margin-right: 20rpx;"></uni-icons>
        <uni-icons type="more" size="24" color="#333" @click="showTaskMenu"></uni-icons>
      </view>
    </view>

    <!-- 任务信息卡片 -->
    <view class="task-card" v-if="taskInfo && Object.keys(taskInfo).length" @click="goToTaskDetail">
      <view class="task-header">
        <text class="task-title">{{ taskInfo?.title || '' }}</text>
        <text class="task-reward">赏金: {{ taskInfo?.reward || '' }}元</text>
      </view>
      <view class="task-details">
        <text class="task-type">任务类型: {{ getTaskTypeText(taskInfo?.type) }}</text>
        <text v-if="taskInfo?.pickupAddress" class="task-location">取件地址: {{ taskInfo?.pickupAddress }}</text>
        <text v-if="taskInfo?.deliveryAddress" class="task-location">送达地址: {{ taskInfo?.deliveryAddress }}</text>
        <text v-if="taskInfo?.expectedDeliveryTime" class="task-time">期望时间: {{ taskInfo?.expectedDeliveryTime }}</text>
      </view>
      <view class="task-status" :class="taskInfo?.status">
        状态: {{ getStatusText(taskInfo?.status) }}
      </view>
    </view>

    <!-- 搜索框 -->
    <view v-if="showSearchBar" class="search-bar">
      <view class="search-input-container">
        <uni-icons type="search" size="20" color="#999"></uni-icons>
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="搜索聊天记录..."
          class="search-input"
          @input="onSearchInput"
          @confirm="performSearch"
        />
        <uni-icons 
          v-if="searchKeyword" 
          type="clear" 
          size="20" 
          color="#999" 
          @click="clearSearch"
        ></uni-icons>
      </view>
    </view>

    <!-- 聊天消息区域 -->
    <scroll-view 
      class="chat-messages" 
      scroll-y="true"
      :scroll-into-view="scrollToId"
      scroll-with-animation
      @scrolltoupper="loadMoreMessages"
    >
      <!-- 加载更多提示 -->
      <view v-if="loadingMore" class="loading-more">
        <uni-icons type="spinner-cycle" size="20" color="#999" class="rotating"></uni-icons>
        <text>加载中...</text>
      </view>
      
      <view 
        v-for="(message, index) in chatMessages" 
        :key="message?._id || index" 
        :id="'msg' + index"
        :class="['message-container', message?.senderId === currentUserId? 'self' : 'other']"
      >
        <!-- 系统消息 -->
        <view v-if="message?.type === 'system'" class="system-message">
          <text>{{ message?.content }}</text>
        </view>
        
        <!-- 交易卡片 -->
        <view v-else-if="message?.type === 'card'" class="trade-card">
          <text class="card-title">{{ message?.title }}</text>
          <text class="card-content">{{ message?.content }}</text>
          <view v-if="message?.status === 'completed' && isPublisher">
            <button class="card-button confirm" @click="confirmTaskCompleted(message)">确认完成</button>
          </view>
          <view v-else-if="message?.status === 'confirmed'">
            <text>任务已确认完成，进入评价</text>
          </view>
        </view>
        
        <!-- 普通消息 -->
        <template v-else>
          <!-- 对方消息 -->
          <view v-if="message?.senderId !== currentUserId" class="other-message">
            <view class="message-avatar-container">
            <image :src="message?.senderAvatar || chatPartner?.avatar || '/static/images/default-avatar.png'" class="message-avatar"></image>
              <text class="sender-name">{{ message?.senderNickname || chatPartner?.nickname || '对方' }}</text>
            </view>
            <view class="message-content">
              <view class="message-bubble other-bubble">
                <!-- 图片消息 -->
                <image 
                  v-if="message?.type === 'image'" 
                  :src="message?.imageUrl" 
                  class="message-image"
                  mode="aspectFit"
                  @click="previewImage(message?.imageUrl)"
                ></image>
                <!-- 位置消息 -->
                <view v-else-if="message?.type === 'location'" class="message-location" @click="openLocation(message?.location)">
                  <view class="location-icon">📍</view>
                  <view class="location-content">
                    <text class="location-name">{{ message?.location?.name || '位置信息' }}</text>
                    <text class="location-address">{{ message?.location?.address || '' }}</text>
                  </view>
                </view>
                <!-- 文本消息 -->
                <text v-else class="message-text">{{ message?.content }}</text>
              </view>
              <view class="message-meta">
                <text class="message-time">{{ formatTime(message?.createTime) }}</text>
              </view>
            </view>
          </view>
          
          <!-- 自己消息 -->
          <view v-else class="self-message">
            <view class="message-content">
              <view class="message-meta">
                <text class="message-time">{{ formatTime(message?.createTime) }}</text>
                <view class="message-status">
                  <uni-icons 
                    v-if="message?.status === 'sending'" 
                    type="spinner-cycle" 
                    size="12" 
                    color="#999"
                    class="rotating"
                  ></uni-icons>
                  <uni-icons 
                    v-else-if="message?.status === 'sent'" 
                    type="checkmark" 
                    size="12" 
                    color="#999"
                  ></uni-icons>
                  <uni-icons 
                    v-else-if="message?.status === 'read'" 
                    type="checkmark-filled" 
                    size="12" 
                    color="#4CAF50"
                  ></uni-icons>
                  <text 
                    v-else-if="message?.status === 'recalled'" 
                    class="recalled-text"
                  >已撤回</text>
                </view>
              </view>
              <view 
                class="message-bubble self-bubble"
                @longpress="showMessageMenu(message)"
              >
                <!-- 图片消息 -->
                <image 
                  v-if="message?.type === 'image'" 
                  :src="message?.imageUrl" 
                  class="message-image"
                  mode="aspectFit"
                  @click="previewImage(message?.imageUrl)"
                ></image>
                <!-- 位置消息 -->
                <view v-else-if="message?.type === 'location'" class="message-location" @click="openLocation(message?.location)">
                  <view class="location-icon">📍</view>
                  <view class="location-content">
                    <text class="location-name">{{ message?.location?.name || '位置信息' }}</text>
                    <text class="location-address">{{ message?.location?.address || '' }}</text>
                  </view>
                </view>
                <!-- 文本消息 -->
                <text v-else class="message-text">{{ message?.content }}</text>
              </view>
            </view>
            <image :src="currentUserAvatar" class="message-avatar"></image>
          </view>
        </template>
      </view>
    </scroll-view>

    <!-- 消息输入区域 -->
    <view class="chat-input-area">
      <view class="input-left">
        <uni-icons type="image" size="28" color="#666" @click="sendImage"></uni-icons>
        <uni-icons type="location-filled" size="28" color="#666" @click="sendLocation"></uni-icons>
      </view>
      <view class="input-center">
        <input 
          v-model="inputMessage" 
          type="text" 
        placeholder="输入消息..."
          class="input-text"
          @confirm="sendTextMessage"
          confirm-type="send"
        />
      </view>
      <view class="input-right">
        <button 
          v-if="showSendCardButton"
          @click="sendTradeCard" 
          class="card-button"
        >
          {{ isPublisher ? '确认派单' : '确认接单' }}
        </button>
        <button 
          v-else
          @click="sendTextMessage" 
          :disabled="!inputMessage.trim() || sending"
          class="send-button"
        >
          {{ sending ? '发送中...' : '发送' }}
      </button>
      </view>
    </view>
    
    <!-- 任务操作菜单 -->
    <uni-popup ref="taskMenu" type="bottom">
      <view class="task-menu">
        <view class="menu-item" @click="viewTaskDetail">
          <uni-icons type="info" size="20" color="#333"></uni-icons>
          <text>查看任务详情</text>
        </view>
        <view class="menu-item" @click="cancelTask" v-if="taskInfo?.status === 'pending'">
          <uni-icons type="close" size="20" color="#F44336"></uni-icons>
          <text>取消任务</text>
        </view>
        <view class="menu-item" @click="completeTask" v-if="taskInfo?.status === 'processing' && isAcceptor">
          <uni-icons type="checkmark" size="20" color="#4CAF50"></uni-icons>
          <text>完成任务</text>
        </view>
        <view class="menu-item" @click="confirmReceipt" v-if="taskInfo?.status === 'processing' && isPublisher">
          <uni-icons type="checkmark" size="20" color="#4CAF50"></uni-icons>
          <text>确认收货</text>
        </view>
        <view class="menu-item" @click="reportProblem">
          <uni-icons type="flag" size="20" color="#FF9800"></uni-icons>
          <text>报告问题</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { normalizeTaskData, getRoleInfo, validateTaskData, debugTaskData } from '@/utils/taskDataMapper.js'

export default {
  data() {
    return {
      // 用户信息
      currentUserId: '',
      currentUserAvatar: '',
      currentUserInfo: {},
      
      // 聊天对象信息
      chatPartner: {
        id: '',
        nickname: '',
        avatar: '',
        online: false
      },
      
      // 聊天数据
      chatMessages: [],
      inputMessage: '',
      scrollToId: '',
      
      // 任务信息
      taskInfo: {},
      taskId: '',
      
      // 用户角色
      isPublisher: false,
      isAcceptor: false,
      
      // 界面状态
      showSendCardButton: false,
      sending: false,
      loadingMore: false,
      hasMoreMessages: true,
      
      // 分页参数
      page: 1,
      pageSize: 20,
      
      // 定时器
      messageTimer: null,
      statusTimer: null,
      
      // 新增：接收 role 参数
      role: '',
      
      // 新增：partnerId
      partnerId: '',
      
      // 新增：taskList
      taskList: [],
      
      // 新增：selectedTask
      selectedTask: {},
      
      // 搜索相关
      showSearchBar: false,
      searchKeyword: '',
      searchResults: [],
      isSearching: false,
      originalMessages: [], // 保存原始消息用于搜索后恢复
      
      // 消息菜单相关
      showMessageMenu: false,
      selectedMessage: null,
    };
  },
  
  computed: {
    taskStatusText() {
      const statusMap = {
        pending: '待确认',
        processing: '进行中',
        completed: '已完成',
        cancelled: '已取消'
      };
      return statusMap[this.taskInfo?.status] || '';
    }
  },
  
  methods: {
    // 获取任务类型文本
    getTaskTypeText(type) {
      const typeMap = {
        'express': '快递代拿',
        'takeout': '外卖代拿',
        'buy': '求购',
        'sell': '出物',
        'other': '其他'
      };
      return typeMap[type] || type;
    },
    
    // 获取状态文本
    getStatusText(status) {
      const map = {
        pending: '待确认',
        processing: '进行中',
        completed: '已完成',
        cancelled: '已取消'
      };
      return map[status] || status;
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      const now = new Date();
      const diff = now - date;
      
      // 今天的消息只显示时间
      if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
        return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
      }
      
      // 昨天的消息显示"昨天"
      if (diff < 48 * 60 * 60 * 1000 && date.getDate() === now.getDate() - 1) {
        return `昨天 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
      }
      
      // 其他显示完整日期
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        const userInfoString = uni.getStorageSync('uni-id-pages-userInfo');
        if (!userInfoString) {
          throw new Error('User information not found in local storage. Please log in again.');
        }
        let userInfo = userInfoString;
        if (typeof userInfoString === 'string') {
          userInfo = JSON.parse(userInfoString);
        }
        if (userInfo && userInfo._id) {
          this.currentUserId = userInfo._id;
          this.currentUserAvatar = (userInfo.avatar_file && userInfo.avatar_file.url) ? userInfo.avatar_file.url : '/static/images/default-avatar.png';
          this.currentUserInfo = userInfo;
          return userInfo;
        } else {
          throw new Error('Invalid user information in local storage.');
        }
      } catch (error) {
        console.error('Failed to get user info:', error);
        uni.showToast({
          title: '获取用户信息异常，请重新登录',
          icon: 'none',
          duration: 2000
        });
        return null;
      }
    },
    
    // 获取聊天对象信息（用于纯私信聊天）
    async getChatPartnerInfo() {
      try {
        const result = await uniCloud.callFunction({
          name: 'getUserInfo',
          data: { userId: this.partnerId }
        });
        
        if (result.result && result.result.code === 200) {
          const userInfo = result.result.data;
          this.chatPartner = {
            id: userInfo._id,
            nickname: userInfo.nickname || '未知用户',
            avatar: (userInfo.avatar_file && userInfo.avatar_file.url) ? userInfo.avatar_file.url : '/static/images/default-avatar.png',
            online: false
          };
          console.log('获取聊天对象信息成功:', this.chatPartner);
        } else {
          console.error('获取聊天对象信息失败:', result.result?.msg);
          // 设置默认信息
          this.chatPartner = {
            id: this.partnerId,
            nickname: '未知用户',
            avatar: '/static/images/default-avatar.png',
            online: false
          };
        }
      } catch (error) {
        console.error('获取聊天对象信息异常:', error);
        // 设置默认信息
        this.chatPartner = {
          id: this.partnerId,
          nickname: '未知用户',
          avatar: '/static/images/default-avatar.png',
          online: false
        };
      }
    },
    
    // 更新聊天对象头像和昵称（从用户信息获取）
    async updateChatPartnerAvatar(userId) {
      try {
        console.log('[头像更新] 尝试获取用户信息，用户ID:', userId);
        const result = await uniCloud.callFunction({
          name: 'getUserInfo',
          data: { userId: userId }
        });
        
        if (result.result && result.result.code === 200) {
          const userInfo = result.result.data;
          const avatarUrl = (userInfo.avatar_file && userInfo.avatar_file.url) ? userInfo.avatar_file.url : '/static/images/default-avatar.png';
          const nickname = userInfo.nickname || userInfo.username || '用户';
          
          // 更新聊天对象头像和昵称
          if (this.chatPartner && this.chatPartner.id === userId) {
            this.chatPartner.avatar = avatarUrl;
            this.chatPartner.nickname = nickname;
            console.log('[头像更新] 成功更新聊天对象信息:', { avatar: avatarUrl, nickname: nickname });
          }
        } else {
          console.error('[头像更新] 获取用户信息失败:', result.result?.msg);
        }
      } catch (error) {
        console.error('[头像更新] 获取用户信息异常:', error);
      }
    },
    
    // 获取任务信息
    async getTaskInfo() {
      try {
        const result = await uniCloud.callFunction({
          name: 'getTaskDetail',
          data: {
            taskId: this.taskId
          }
        });
        
        if (result.result.code === 200) {
          this.taskInfo = result.result.data;
          
          // 这部分逻辑依然需要，但它不再重新判断和设置 isPublisher/isAcceptor
          // 而是基于已经固定的身份，来更新聊天对象的信息
          if (this.isPublisher) {
            // 发布者，聊天对象是领取者
            this.chatPartner = {
              id: this.taskInfo.acceptor_id,
              nickname: this.taskInfo.acceptor_name || '任务领取者',
              avatar: this.taskInfo.acceptor_avatar || '/static/images/avatar2.png',
              online: false
            };
          } else {
            // 领取者，聊天对象是发布者
            this.chatPartner = {
              id: this.taskInfo.publisher_id,
              nickname: this.taskInfo.publisher_name,
              avatar: this.taskInfo.publisher_avatar,
              online: false
            };
          }
          
          // 根据最新的任务状态和固定的身份，更新按钮的可见性
          if (this.isPublisher && this.taskInfo.status === 'pending') {
            this.showSendCardButton = true;
          } else if (this.isAcceptor && this.taskInfo.status === 'pending') {
            this.showSendCardButton = true;
          } else {
            this.showSendCardButton = false;
          }
        }
      } catch (error) {
        console.error('获取任务信息失败:', error);
        uni.showToast({
          title: '获取任务信息失败',
          icon: 'none'
        });
      }
    },

    // 加载更多消息
    async loadMoreMessages() {
      if (this.loadingMore || !this.hasMoreMessages) return;
      
      this.loadingMore = true;
      this.page++;
      
      try {
        await this.getAllMessagesWithPartner();
      } finally {
        this.loadingMore = false;
      }
    },
    
    // 发送文本消息
    async sendTextMessage() {
      if (this.inputMessage.trim() === '' || this.sending) return;
      
      const content = this.inputMessage.trim();
      this.inputMessage = '';
      this.sending = true;
      
      // 先添加到本地显示
      const tempMessage = {
        _id: 'temp_' + Date.now(),
    type: 'text',
        senderId: this.currentUserId,
        senderAvatar: this.currentUserAvatar,
        content: content,
        createTime: new Date().toISOString(),
        status: 'sending'
      };
      
      this.chatMessages.push(tempMessage);
      this.scrollToBottom();
      
      try {
        // 调用云函数发送消息
        const messageData = {
          senderId: this.currentUserId,
          senderNickname: this.currentUserInfo.nickname,
          senderAvatar: this.currentUserAvatar,
          receiverId: this.partnerId,
          content,
          type: 'text'
        };
        
        // 如果有任务ID，添加到数据中
        if (this.taskId) {
          messageData.taskId = this.taskId;
        }
        
        console.log('[Chat] 发送消息数据:', messageData);
        console.log('[Chat] 当前taskId:', this.taskId);
        console.log('[Chat] 当前partnerId:', this.partnerId);
        
        const res = await uniCloud.callFunction({
          name: 'sendChatMessage',
          data: messageData
        });
        
        if (res.result.code === 200) {
          // 更新消息状态
          const index = this.chatMessages.findIndex(msg => msg._id === tempMessage._id);
          if (index !== -1) {
            this.chatMessages[index] = {
              ...res.result.data,
              status: 'sent'
            };
          }
        } else {
          throw new Error(res.result.msg || '发送失败');
        }
      } catch (error) {
        console.error('发送消息失败:', error);
        
        // 更新消息状态为失败
        const index = this.chatMessages.findIndex(msg => msg._id === tempMessage._id);
        if (index !== -1) {
          this.chatMessages[index].status = 'failed';
        }
        
        uni.showToast({
          title: '发送失败',
          icon: 'none'
        });
      } finally {
        this.sending = false;
      }
    },
    
    // 发送交易确认卡片
    async sendTradeCard() {
      // 根据用户角色和任务状态生成不同的卡片内容
      let cardTitle = '';
      let cardContent = '';
      
      if (this.isPublisher) {
        // 发布者发送确认派单卡片
        cardTitle = '确认派单';
        cardContent = '我已确认将此任务派发给你，请开始执行任务。';
      } else {
        // 领取者发送接单确认卡片
        cardTitle = '任务确认';
        cardContent = '我已准备好执行任务，请确认将此任务派发给我';
      }
      
      try {
        const result = await uniCloud.callFunction({
          name: 'sendChatMessage',
          data: {
            taskId: this.taskId,
            content: cardContent,
            type: 'card',
            title: cardTitle,
            status: 'pending',
            receiverId: this.chatPartner.id
          }
        });
        
        if (result.result.code === 200) {
          this.chatMessages.push(result.result.data);
          this.scrollToBottom();
          
          // 如果是发布者发送的确认卡片，更新任务状态
          if (this.isPublisher) {
            this.taskInfo.status = 'processing';
            this.showSendCardButton = false;
          }
        }
      } catch (error) {
        console.error('发送交易卡失败:', error);
        uni.showToast({
          title: '发送失败',
          icon: 'none'
        });
      }
    },
    
    // 确认任务（发布者操作）
    async confirmTask(cardMessage) {
      try {
        // 更新卡片状态
        const result = await uniCloud.callFunction({
          name: 'updateTaskStatus',
          data: {
            taskId: this.taskId,
            status: 'processing',
            messageId: cardMessage._id
          }
        });
        
        if (result.result.code === 200) {
          // 更新本地状态
          cardMessage.status = 'confirmed';
          this.taskInfo.status = 'processing';
          this.showSendCardButton = false;
          
          // 添加系统消息
          this.chatMessages.push({
            type: 'system',
            content: `${this.chatPartner.nickname} 已确认任务派发`,
            createTime: new Date().toISOString()
          });
          
          this.scrollToBottom();
          
          uni.showToast({
            title: '任务已确认派发',
            icon: 'success'
          });
        }
      } catch (error) {
        console.error('确认任务失败:', error);
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }
    },
    
    // 接受任务（领取者操作）
    async acceptTask(cardMessage) {
      try {
        // 更新卡片状态
        const result = await uniCloud.callFunction({
          name: 'updateTaskStatus',
          data: {
            taskId: this.taskId,
            status: 'processing',
            messageId: cardMessage._id
          }
        });
        
        if (result.result.code === 200) {
          // 更新本地状态
          cardMessage.status = 'confirmed';
          this.taskInfo.status = 'processing';
          
          // 添加系统消息
          this.chatMessages.push({
            type: 'system',
            content: `你已确认接受任务`,
            createTime: new Date().toISOString()
          });
          
          this.scrollToBottom();
          
          uni.showToast({
            title: '任务已确认接受',
            icon: 'success'
          });
        }
      } catch (error) {
        console.error('接受任务失败:', error);
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        if (this.chatMessages.length > 0) {
          this.scrollToId = 'msg' + (this.chatMessages.length - 1);
        }
      });
    },
    
    // 显示任务操作菜单
    showTaskMenu() {
      this.$refs.taskMenu.open();
    },
    
    // 获取卡片状态文本
    getCardStatusText(status) {
      const statusMap = {
        'confirmed': '任务已确认',
        'cancelled': '任务已取消',
        'pending': '等待确认'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 查看任务详情
    viewTaskDetail() {
      console.log('[Chat.vue] 准备通过 eventChannel 发送任务数据:', this.taskInfo);
      uni.navigateTo({
        url: `/pages/task/TaskDetail/TaskDetail?id=${this.taskId}`,
        success: (res) => {
          // 通过 eventChannel 向详情页传递任务数据
          res.eventChannel.emit('taskData', { task: this.taskInfo })
        }
      })
    },
    
    // 取消任务
    async cancelTask() {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消这个任务吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await uniCloud.callFunction({
                name: 'updateTaskStatus',
                data: {
                  taskId: this.taskId,
                  status: 'cancelled'
                }
              });
              
              if (result.result.code === 200) {
                this.taskInfo.status = 'cancelled';
                uni.showToast({
                  title: '任务已取消',
                  icon: 'success'
                });
              }
            } catch (error) {
              console.error('取消任务失败:', error);
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 完成任务
    async completeTask() {
      uni.showModal({
        title: '确认完成',
        content: '确定任务已完成吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await uniCloud.callFunction({
                name: 'updateTaskStatus',
                data: {
                  taskId: this.taskId,
                  status: 'completed'
                }
              });
              
              if (result.result.code === 200) {
                this.taskInfo.status = 'completed';
                uni.showToast({
                  title: '任务已完成',
                  icon: 'success'
                });
              }
            } catch (error) {
              console.error('完成任务失败:', error);
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 确认收货
    async confirmReceipt() {
      uni.showModal({
        title: '确认收货',
        content: '确认已收到任务成果吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await uniCloud.callFunction({
                name: 'updateTaskStatus',
                data: {
                  taskId: this.taskId,
                  status: 'completed'
                }
              });
              
              if (result.result.code === 200) {
                this.taskInfo.status = 'completed';
                uni.showToast({
                  title: '确认成功',
                  icon: 'success'
                });
              }
            } catch (error) {
              console.error('确认收货失败:', error);
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 报告问题
    reportProblem() {
      uni.navigateTo({
        url: `/pages/report/report?taskId=${this.taskId}`
      });
    },
    
    // 发送图片
    async sendImage() {
      try {
        const res = await uni.chooseImage({
          count: 1,
          sizeType: ['compressed'], // 使用压缩图片
          sourceType: ['album', 'camera'] // 相册和相机
        });
        
        if (res.tempFilePaths && res.tempFilePaths.length > 0) {
          const tempFilePath = res.tempFilePaths[0];
          
          // 显示加载状态
          uni.showLoading({
            title: '发送中...'
          });
          
          // 先添加到本地显示
          const tempMessage = {
            _id: 'temp_' + Date.now(),
            type: 'image',
            senderId: this.currentUserId,
            senderAvatar: this.currentUserAvatar,
            imageUrl: tempFilePath,
            createTime: new Date().toISOString(),
            status: 'sending'
          };
          
          this.chatMessages.push(tempMessage);
          this.scrollToBottom();
          
          try {
            // 上传图片到云存储
            const uploadResult = await uniCloud.uploadFile({
              filePath: tempFilePath,
              cloudPath: `chat-images/${Date.now()}-${Math.random().toString(36).substr(2, 9)}.jpg`
            });
            
            if (uploadResult.fileID) {
              // 发送图片消息
              const messageData = {
                senderId: this.currentUserId,
                senderNickname: this.currentUserInfo.nickname,
                senderAvatar: this.currentUserAvatar,
                receiverId: this.partnerId,
                content: '[图片]',
                type: 'image',
                imageUrl: uploadResult.fileID
              };
              
              // 如果有任务ID，添加到数据中
              if (this.taskId) {
                messageData.taskId = this.taskId;
              }
              
              const sendResult = await uniCloud.callFunction({
                name: 'sendChatMessage',
                data: messageData
              });
              
              if (sendResult.result.code === 200) {
                // 更新消息状态
                const index = this.chatMessages.findIndex(msg => msg._id === tempMessage._id);
                if (index !== -1) {
                  this.chatMessages[index] = {
                    ...sendResult.result.data,
                    status: 'sent'
                  };
                }
                uni.hideLoading();
              } else {
                throw new Error(sendResult.result.msg || '发送失败');
              }
            } else {
              throw new Error('图片上传失败');
            }
          } catch (error) {
            console.error('发送图片失败:', error);
            // 更新消息状态为失败
            const index = this.chatMessages.findIndex(msg => msg._id === tempMessage._id);
            if (index !== -1) {
              this.chatMessages[index].status = 'failed';
            }
            uni.hideLoading();
            uni.showToast({
              title: '发送失败',
              icon: 'none'
            });
          }
        }
      } catch (error) {
        console.error('选择图片失败:', error);
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    },
    
    // 预览图片
    previewImage(imageUrl) {
      if (!imageUrl) return;
      
      uni.previewImage({
        urls: [imageUrl],
        current: imageUrl
      });
    },
    
    // 打开位置
    openLocation(location) {
      if (!location || !location.latitude || !location.longitude) {
        uni.showToast({
          title: '位置信息无效',
          icon: 'none'
        });
        return;
      }
      
      uni.openLocation({
        latitude: parseFloat(location.latitude),
        longitude: parseFloat(location.longitude),
        name: location.name || '位置',
        address: location.address || '',
        success: () => {
          console.log('打开位置成功');
        },
        fail: (error) => {
          console.error('打开位置失败:', error);
          uni.showToast({
            title: '打开位置失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 发送位置
    async sendLocation() {
      try {
        const res = await uni.chooseLocation({
          success: (locationRes) => {
            // 这里可以调用云函数发送位置信息
            console.log('选择位置:', locationRes);
          }
        });
        
        if (res && res.name) {
          // 显示加载状态
          uni.showLoading({
            title: '发送中...'
          });
          
          // 先添加到本地显示
          const tempMessage = {
            _id: 'temp_' + Date.now(),
            type: 'location',
            senderId: this.currentUserId,
            senderAvatar: this.currentUserAvatar,
            content: `[位置] ${res.name}`,
            location: {
              latitude: res.latitude,
              longitude: res.longitude,
              address: res.address,
              name: res.name
            },
            createTime: new Date().toISOString(),
            status: 'sending'
          };
          
          this.chatMessages.push(tempMessage);
          this.scrollToBottom();
          
          try {
            // 发送位置消息
            const messageData = {
              senderId: this.currentUserId,
              senderNickname: this.currentUserInfo.nickname,
              senderAvatar: this.currentUserAvatar,
              receiverId: this.partnerId,
              content: `[位置] ${res.name}`,
              type: 'location',
              location: {
                latitude: res.latitude,
                longitude: res.longitude,
                address: res.address,
                name: res.name
              }
            };
            
            // 如果有任务ID，添加到数据中
            if (this.taskId) {
              messageData.taskId = this.taskId;
            }
            
            const sendResult = await uniCloud.callFunction({
              name: 'sendChatMessage',
              data: messageData
            });
            
            if (sendResult.result.code === 200) {
              // 更新消息状态
              const index = this.chatMessages.findIndex(msg => msg._id === tempMessage._id);
              if (index !== -1) {
                this.chatMessages[index] = {
                  ...sendResult.result.data,
                  status: 'sent'
                };
              }
              uni.hideLoading();
            } else {
              throw new Error(sendResult.result.msg || '发送失败');
            }
          } catch (error) {
            console.error('发送位置失败:', error);
            // 更新消息状态为失败
            const index = this.chatMessages.findIndex(msg => msg._id === tempMessage._id);
            if (index !== -1) {
              this.chatMessages[index].status = 'failed';
            }
            uni.hideLoading();
            uni.showToast({
              title: '发送失败',
              icon: 'none'
            });
          }
        }
      } catch (error) {
        console.error('选择位置失败:', error);
        uni.showToast({
          title: '选择位置失败',
          icon: 'none'
        });
      }
    },
    
    // 定时刷新消息
    startMessageTimer() {
      this.messageTimer = setInterval(async () => {
        await this.getAllMessagesWithPartner();
      }, 5000); // 每5秒刷新一次
    },
    
    // 停止定时器
    stopMessageTimer() {
      if (this.messageTimer) {
        clearInterval(this.messageTimer);
        this.messageTimer = null;
      }
      if (this.statusTimer) {
        clearInterval(this.statusTimer);
        this.statusTimer = null;
      }
    },
    
    // 如果是领取者且没有聊天记录，自动发送初始消息
    async sendInitialMessage() {
      try {
        // 根据任务类型生成不同的初始消息
        let messageContent = '';
        switch (this.taskInfo.type) {
          case 'express':
            messageContent = `你好！关于你发布的快递代拿任务，我可以接单。请问有什么需要注意的吗？`;
            break;
          case 'takeout':
            messageContent = `你好！关于你发布的外卖代拿任务，我可以接单。请问有什么需要注意的吗？`;
            break;
          case 'buy':
            messageContent = `你好！关于你发布的求购任务，我可以帮你寻找。请问有什么具体要求吗？`;
            break;
          case 'sell':
            messageContent = `你好！关于你发布的出物任务，我可以帮你处理。请问有什么需要注意的吗？`;
            break;
          default:
            messageContent = `你好！关于你发布的任务，我可以接单。请问有什么需要注意的吗？`;
        }
        
        const result = await uniCloud.callFunction({
          name: 'sendChatMessage',
          data: {
            taskId: this.taskId,
            content: messageContent,
            type: 'text',
            receiverId: this.chatPartner.id
          }
        });
        
        if (result.result.code === 200) {
          // 将发送的消息添加到本地聊天记录
          const sentMessage = {
            _id: result.result.data._id,
            type: 'text',
            senderId: this.currentUserId,
            senderAvatar: this.currentUserAvatar,
            content: messageContent,
            createTime: new Date().toISOString(),
            status: 'sent'
          };
          
          this.chatMessages.push(sentMessage);
          this.scrollToBottom();
          
          // 显示发送成功提示
          uni.showToast({
            title: '初始消息已发送',
            icon: 'success',
            duration: 1500
          });
        }
      } catch (error) {
        console.error('发送初始消息失败:', error);
        uni.showToast({
          title: '发送初始消息失败',
          icon: 'none'
        });
      }
    },
    
    // 获取对方信息
    async getPartnerInfo() {
      const res = await uniCloud.callFunction({
        name: 'getUserInfo',
        data: { userId: this.partnerId }
      });
      if (res.result.code === 200) {
        this.chatPartner = {
          id: this.partnerId,
          nickname: res.result.data.nickname,
          avatar: res.result.data.avatar_file?.url || '/static/images/default-avatar.png',
          online: false
        };
      }
    },
    
    // 获取所有任务
    async getAllTasksWithPartner() {
      const res = await uniCloud.callFunction({
        name: 'getTaskListWithUser',
        data: {
          userA: this.currentUserId,
          userB: this.partnerId
        }
      });
      if (res.result.code === 200) {
        this.taskList = res.result.data;
        this.selectedTask = this.taskList[0] || null;
      }
    },
    
    // 获取所有消息
    async getAllMessagesWithPartner() {
      const res = await uniCloud.callFunction({
        name: 'getChatMessagesWithUser',
        data: {
          userA: this.currentUserId,
          userB: this.partnerId
        }
      });
      if (res.result.code === 200) {
        this.chatMessages = res.result.data;
        this.chatMessages = this.chatMessages.map(msg => {
          if (msg.senderId !== this.currentUserId && !msg.senderNickname) {
            return { ...msg, senderNickname: this.chatPartner.nickname }
          }
          return msg
        });
        this.$nextTick(() => this.scrollToBottom());
      }
    },
    
    // 切换任务卡片
    selectTask(task) {
      this.selectedTask = task;
    },
    
    async markTaskCompleted() {
      // 1. 更新任务状态为 completed
      await uniCloud.callFunction({
        name: 'updateTaskStatus',
        data: { taskId: this.taskId, status: 'completed' }
      })
      // 2. 发送交易卡片到聊天页
      await uniCloud.callFunction({
        name: 'sendChatMessage',
        data: {
          taskId: this.taskId,
          type: 'card',
          title: '任务完成',
          content: '我已完成任务，请确认。',
          status: 'completed',
          receiverId: this.partnerId
        }
      })
      uni.showToast({ title: '已通知发布者确认', icon: 'success' })
      // 3. 可选：跳转回聊天页
      uni.navigateTo({
        url: `/pages/message/Chat/Chat?taskId=${this.taskId}&partnerId=${this.partnerId}&role=acceptor`
      })
    },
    
    async confirmTaskCompleted(cardMessage) {
      // 1. 更新任务状态为 confirmed
      await uniCloud.callFunction({
        name: 'updateTaskStatus',
        data: { taskId: this.taskId, status: 'confirmed', messageId: cardMessage._id }
      })
      // 2. 更新本地消息状态
      cardMessage.status = 'confirmed'
      // 3. 跳转到评价页
      uni.navigateTo({
        url: `/pages/task/TaskDetail/TaskDetail?id=${this.taskId}&showComment=1`
      })
    },
    
    goToTaskDetail() {
      console.log('[Chat.vue] 准备通过 eventChannel 发送任务数据:', this.taskInfo);
      uni.navigateTo({
        url: `/pages/task/TaskDetail/TaskDetail?id=${this.taskId}`,
        success: (res) => {
          // 通过 eventChannel 向详情页传递任务数据
          res.eventChannel.emit('taskData', { task: this.taskInfo })
        }
      })
    },
    
    // 标记所有未读消息为已读
    async markAllMessagesAsRead() {
      try {
        // 找到所有未读的消息
        const unreadMessages = this.chatMessages.filter(msg => 
          msg.receiverId === this.currentUserId && 
          msg.status !== 'read' && 
          msg.status !== 'sending'
        );
        
        if (unreadMessages.length === 0) {
          return;
        }
        
        console.log('标记未读消息为已读:', unreadMessages.length, '条');
        
        // 批量标记消息为已读
        for (const message of unreadMessages) {
          try {
            await uniCloud.callFunction({
              name: 'markChatMessageRead',
              data: {
                messageId: message._id,
                userId: this.currentUserId
              }
            });
            
            // 更新本地消息状态
            const index = this.chatMessages.findIndex(msg => msg._id === message._id);
            if (index !== -1) {
              this.chatMessages[index].status = 'read';
            }
          } catch (error) {
            console.error('标记消息已读失败:', message._id, error);
          }
        }
      } catch (error) {
        console.error('批量标记消息已读失败:', error);
      }
    },
    
    // 搜索相关方法
    toggleSearch() {
      this.showSearchBar = !this.showSearchBar;
      if (!this.showSearchBar) {
        // 关闭搜索时恢复原始消息
        this.clearSearch();
      }
    },
    
    onSearchInput() {
      // 实时搜索
      if (this.searchKeyword.trim()) {
        this.performSearch();
      } else {
        this.clearSearch();
      }
    },
    
    performSearch() {
      if (!this.searchKeyword.trim()) {
        this.clearSearch();
        return;
      }
      
      this.isSearching = true;
      
      // 保存原始消息（如果还没有保存）
      if (this.originalMessages.length === 0) {
        this.originalMessages = [...this.chatMessages];
      }
      
      // 搜索消息
      const keyword = this.searchKeyword.toLowerCase();
      this.searchResults = this.originalMessages.filter(message => {
        // 搜索文本内容
        if (message.content && message.content.toLowerCase().includes(keyword)) {
          return true;
        }
        // 搜索发送者昵称
        if (message.senderNickname && message.senderNickname.toLowerCase().includes(keyword)) {
          return true;
        }
        // 搜索位置名称
        if (message.location && message.location.name && message.location.name.toLowerCase().includes(keyword)) {
          return true;
        }
        return false;
      });
      
      // 显示搜索结果
      this.chatMessages = this.searchResults;
      
      console.log('搜索结果:', this.searchResults.length, '条');
    },
    
    clearSearch() {
      this.searchKeyword = '';
      this.isSearching = false;
      this.searchResults = [];
      
      // 恢复原始消息
      if (this.originalMessages.length > 0) {
        this.chatMessages = [...this.originalMessages];
        this.originalMessages = [];
      }
    },
    
    // 显示消息菜单
    showMessageMenu(message) {
      if (!message || message.senderId !== this.currentUserId) {
        return;
      }
      
      // 检查消息是否可以撤回（2分钟内且状态为sent或read）
      const messageTime = new Date(message.createTime);
      const now = new Date();
      const timeDiff = now - messageTime;
      const twoMinutes = 2 * 60 * 1000;
      
      const canRecall = timeDiff <= twoMinutes && 
                       (message.status === 'sent' || message.status === 'read') &&
                       message.status !== 'recalled';
      
      this.selectedMessage = message;
      
      const menuItems = [];
      if (canRecall) {
        menuItems.push('撤回消息');
      }
      menuItems.push('复制消息');
      
      uni.showActionSheet({
        itemList: menuItems,
        success: (res) => {
          if (menuItems[res.tapIndex] === '撤回消息') {
            this.recallMessage(message);
          } else if (menuItems[res.tapIndex] === '复制消息') {
            this.copyMessage(message);
          }
        }
      });
    },
    
    // 撤回消息
    async recallMessage(message) {
      try {
        uni.showLoading({
          title: '撤回中...'
        });
        
        const result = await uniCloud.callFunction({
          name: 'recallChatMessage',
          data: {
            messageId: message._id,
            userId: this.currentUserId
          }
        });
        
        uni.hideLoading();
        
        if (result.result.code === 200) {
          // 更新本地消息状态
          const index = this.chatMessages.findIndex(msg => msg._id === message._id);
          if (index !== -1) {
            this.chatMessages[index].status = 'recalled';
            this.chatMessages[index].content = '[消息已撤回]';
          }
          
          uni.showToast({
            title: '撤回成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: result.result.msg || '撤回失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('撤回消息失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '撤回失败',
          icon: 'none'
        });
      }
    },
    
    // 复制消息
    copyMessage(message) {
      let textToCopy = '';
      
      if (message.type === 'image') {
        textToCopy = '[图片]';
      } else if (message.type === 'location') {
        textToCopy = `[位置] ${message.location?.name || '位置信息'}`;
      } else {
        textToCopy = message.content || '';
      }
      
      uni.setClipboardData({
        data: textToCopy,
        success: () => {
          uni.showToast({
            title: '已复制到剪贴板',
            icon: 'success'
          });
        },
        fail: () => {
          uni.showToast({
            title: '复制失败',
            icon: 'none'
          });
        }
      });
    }
  },
  
  async onLoad(options) {
    console.log('🔍 [Chat] 接收到的完整options:', options);
    
    // 获取路由参数
    this.taskId = options.taskId || options.id;
    this.role = options.role || ''; // 从跳转中获取预设的角色
    this.partnerId = options.partnerId;
    
    // 获取从消息中心传递的聊天对象信息
    const partnerAvatar = options.partnerAvatar ? decodeURIComponent(options.partnerAvatar) : null;
    const partnerNickname = options.partnerNickname ? decodeURIComponent(options.partnerNickname) : null;
    
    console.log('[Chat] 接收到的聊天对象信息:', { 
      partnerId: this.partnerId, 
      partnerAvatar, 
      partnerNickname 
    });
    console.log('[Chat] 原始参数:', {
      taskId: options.taskId,
      id: options.id,
      partnerId: options.partnerId,
      partnerAvatar: options.partnerAvatar,
      partnerNickname: options.partnerNickname
    });
    
    // 检查是否有必要的参数（taskId或partnerId）
    if (!this.taskId && !this.partnerId) {
      uni.showToast({
        title: '缺少必要参数',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }
    
    // 1. 首先，可靠地获取当前用户信息
    const userInfo = await this.getUserInfo();
    if (!userInfo) {
      // 如果获取用户信息失败，则中断后续操作并返回上一页
      setTimeout(() => { uni.navigateBack(); }, 2000);
      return;
    }

    // 2. 获取任务信息（如果有taskId）
    if (this.taskId) {
      const initialTaskResult = await uniCloud.callFunction({
        name: 'getTaskDetail',
        data: { taskId: this.taskId }
      });

      if (initialTaskResult.result.code !== 200) {
        uni.showToast({ title: '无法获取任务信息', icon: 'none' });
        uni.navigateBack();
        return;
      }
      this.taskInfo = initialTaskResult.result.data;

      // 3. 【核心】使用统一的数据映射和角色判断逻辑
      console.log('[角色判断] 开始角色判断流程');
      console.log('[角色判断] 当前用户ID:', this.currentUserId);
      console.log('[角色判断] URL参数role:', this.role);
      
      // 标准化任务数据
      const normalizedTaskData = normalizeTaskData(this.taskInfo, this.taskInfo.type || 'other');
      debugTaskData(normalizedTaskData, 'Chat页面');
      
      // 验证数据完整性
      const validation = validateTaskData(normalizedTaskData);
      if (!validation.isValid) {
        console.error('[角色判断] 任务数据验证失败:', validation.errors);
        uni.showToast({
          title: '任务数据异常，请重试',
          icon: 'none'
        });
        uni.navigateBack();
        return;
      }
      
      // 使用统一的角色判断逻辑
      const roleInfo = getRoleInfo(normalizedTaskData, this.currentUserId);
      
      // 如果URL中明确指定了角色，优先使用URL参数
      if (this.role === 'acceptor') {
        this.isAcceptor = true;
          this.isPublisher = false;
        console.log('[角色判断] 根据URL参数设置为接收者');
      } else if (this.role === 'publisher') {
        this.isPublisher = true;
          this.isAcceptor = false;
        console.log('[角色判断] 根据URL参数设置为发布者');
      } else {
        // 使用数据驱动的角色判断
        this.isPublisher = roleInfo.role === 'publisher';
        this.isAcceptor = roleInfo.role === 'acceptor';
        console.log('[角色判断] 根据数据判断角色:', roleInfo.role);
      }
      
      console.log('[角色判断] 最终角色:', this.isPublisher ? 'publisher' : (this.isAcceptor ? 'acceptor' : 'user'));

      // 4. 根据已确定的身份，初始化聊天对象信息
      if (roleInfo.partner) {
        this.chatPartner = {
          id: roleInfo.partner.id,
          nickname: roleInfo.partner.name,
          avatar: roleInfo.partner.avatar,
          online: false
        };
        console.log('[角色判断] 聊天对象信息:', this.chatPartner);
        
        // 优先使用从消息中心传递的头像和昵称信息
        if (partnerAvatar && partnerNickname) {
          this.chatPartner.avatar = partnerAvatar;
          this.chatPartner.nickname = partnerNickname;
          console.log('[Chat] 使用消息中心传递的聊天对象信息:', { 
            avatar: partnerAvatar, 
            nickname: partnerNickname 
          });
        } else if (!roleInfo.partner.avatar || roleInfo.partner.avatar === '/static/images/default-avatar.png') {
          // 如果头像不完整，尝试从用户信息获取
          await this.updateChatPartnerAvatar(roleInfo.partner.id);
        }
      } else {
        console.warn('[角色判断] 未找到聊天对象信息');
        this.chatPartner = {
          id: '',
          nickname: '未知用户',
          avatar: '/static/images/default-avatar.png',
          online: false
        };
      }
      if (this.isPublisher && this.taskInfo.status === 'pending') {
        this.showSendCardButton = true;
      } else if (this.isAcceptor && this.taskInfo.status === 'pending') {
        this.showSendCardButton = true;
      } else {
        this.showSendCardButton = false;
      }
    } else {
      // 纯私信聊天模式
      this.isPublisher = false;
      this.isAcceptor = false;
      this.showSendCardButton = false;
      
      // 优先使用从消息中心传递的聊天对象信息
      if (partnerAvatar && partnerNickname && this.partnerId) {
        this.chatPartner = {
          id: this.partnerId,
          nickname: partnerNickname,
          avatar: partnerAvatar,
          online: false
        };
        console.log('[Chat] 纯私信模式使用消息中心传递的聊天对象信息:', this.chatPartner);
      } else if (this.partnerId) {
        // 如果没有传递信息，则获取聊天对象信息
        await this.getChatPartnerInfo();
      }
    }

    // 5. 获取历史聊天消息
    await this.getAllMessagesWithPartner();

    // 6. 如果是领取者且没有聊天记录，自动发送初始消息
    if (this.isAcceptor && this.chatMessages.length === 0) {
      await this.sendInitialMessage();
    }

    // 7. 启动定时刷新
    this.startMessageTimer();

    // 8. 获取对方信息（仅在纯私信聊天模式下）
    if (!this.taskId && this.partnerId) {
      await this.getPartnerInfo();
    }

    // 9. 获取所有任务
    await this.getAllTasksWithPartner();

    // 10. 获取所有消息
    await this.getAllMessagesWithPartner();
  },
  
  onUnload() {
    // 停止定时器
    this.stopMessageTimer();
  },
  
  onShow() {
    if (this.partnerId) {
      this.getAllMessagesWithPartner();
      // 标记所有未读消息为已读
      this.markAllMessagesAsRead();
    }
  }
};
</script>

<style lang="scss">
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
  
  /* #ifdef H5 */
  background: url('/static/images/chat-backgrounds/微信图片_20250917164430.jpg') center/cover no-repeat;
  background-attachment: fixed;
  /* #endif */
  
  /* #ifdef MP-WEIXIN */
  background: url('~@/static/images/chat-backgrounds/微信图片_20250917164430.jpg') center/cover no-repeat;
  /* #endif */
}

.chat-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(1px);
  z-index: 0;
}

.chat-container > view{
  position: relative;
  z-index: 1;
}
.background-image {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}
.chat-header {
  height: 120rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .chat-header-left, .chat-header-right {
    width: 80rpx;
    display: flex;
    justify-content: center;
  }
  
  .chat-header-middle {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .chat-avatar {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    margin-bottom: 5rpx;
    border: 2rpx solid rgba(255, 255, 255, 0.8);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
  
  .chat-username {
    font-size: 30rpx;
    font-weight: 600;
    color: #333;
    text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
  }
  
  .chat-status {
    font-size: 24rpx;
    color: #4CAF50;
    font-weight: 500;
  }
}

.task-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20rpx;
  padding: 25rpx;
  margin: 20rpx;
  box-shadow: 0 8rpx 25rpx rgba(0,0,0,0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  
  .task-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15rpx;
  }
  
  .task-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .task-reward {
    font-size: 28rpx;
    color: #FF5722;
    font-weight: bold;
  }
  
  .task-details {
    display: flex;
    flex-direction: column;
    margin-bottom: 15rpx;
    
    text {
      font-size: 26rpx;
      color: #666;
      margin-bottom: 8rpx;
    }
  }
  
  .task-status {
    font-size: 26rpx;
    padding: 8rpx 15rpx;
    border-radius: 20rpx;
    background: #f5f5f5;
    text-align: center;
    
    &.pending {
      color: #FF9800;
      background: #FFF8E1;
    }
    
    &.processing {
      color: #2196F3;
      background: #E3F2FD;
    }
    
    &.completed {
      color: #4CAF50;
      background: #E8F5E9;
    }
    
    &.cancelled {
      color: #F44336;
      background: #FFEBEE;
    }
  }
}

.chat-messages {
  flex: 1;
  overflow: hidden;
  padding: 20rpx;
  box-sizing: border-box;
  background: transparent;
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  color: #999;
  font-size: 26rpx;
  
  text {
    margin-left: 10rpx;
  }
}

.message-container {
  margin-bottom: 40rpx;
  
  .system-message {
    text-align: center;
    padding: 15rpx 20rpx;
    
    text {
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.8);
      background: rgba(255, 255, 255, 0.2);
      padding: 8rpx 20rpx;
      border-radius: 25rpx;
      backdrop-filter: blur(10px);
    }
  }
  
  .trade-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 20rpx;
    padding: 25rpx;
    box-shadow: 0 8rpx 25rpx rgba(0,0,0,0.1);
    border: 1rpx solid rgba(255, 255, 255, 0.2);
    
    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      display: block;
      margin-bottom: 15rpx;
    }
    
    .card-content {
      font-size: 28rpx;
      color: #666;
      display: block;
      margin-bottom: 20rpx;
    }

    .card-actions {
      display: flex;
      justify-content: center;
    }
    
    .card-result {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10rpx;
      font-size: 28rpx;
      color: #4CAF50;
      
      text {
        margin-left: 10rpx;
      }
    }
  }
  
  .card-button {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 40rpx;
    padding: 0 40rpx;
    height: 70rpx;
    line-height: 70rpx;
    font-size: 28rpx;
    box-shadow: 0 4rpx 15rpx rgba(102, 126, 234, 0.3);
    
    &.confirm {
      background: linear-gradient(135deg, #2196F3 0%, #21CBF3 100%);
    }
  }
  
  .other-message {
    display: flex;
    align-items: flex-start;
    margin-bottom: 24rpx;
    
    .message-avatar-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 16rpx;
      min-width: 80rpx;
    }
    
    .message-avatar {
      width: 64rpx;
      height: 64rpx;
      border-radius: 50%;
      border: 2rpx solid rgba(77, 124, 191, 0.15);
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
      flex-shrink: 0;
    }
    
    .message-content {
      max-width: 75%;
      display: flex;
      flex-direction: column;
    }
  }
  
  .self-message {
    display: flex;
    justify-content: flex-end;
    align-items: flex-start;
    margin-bottom: 24rpx;
    
    .message-avatar {
      width: 64rpx;
      height: 64rpx;
      border-radius: 50%;
      margin-left: 16rpx;
      border: 2rpx solid rgba(77, 124, 191, 0.15);
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
      flex-shrink: 0;
    }
    
    .message-content {
      max-width: 75%;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
    }
  }
  
  .message-bubble {
    position: relative;
    padding: 24rpx 28rpx;
    border-radius: 16rpx;
    min-height: 60rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    word-wrap: break-word;
    word-break: break-all;
    transition: all 0.2s ease;
  }

  .other-bubble {
    background: rgba(255, 255, 255, 0.95);
    border-top-left-radius: 6rpx;
    border: 1rpx solid rgba(77, 124, 191, 0.1);
    color: #1D2129;
    
    &::before {
      content: '';
      position: absolute;
      left: -8rpx;
      top: 20rpx;
      width: 0;
      height: 0;
      border-top: 8rpx solid transparent;
      border-bottom: 8rpx solid transparent;
      border-right: 8rpx solid rgba(255, 255, 255, 0.95);
    }
  }

  .self-bubble {
    background: linear-gradient(135deg, #4D7CBF 0%, #3A5F95 100%);
    border-top-right-radius: 6rpx;
    color: white;
    box-shadow: 0 2rpx 8rpx rgba(77, 124, 191, 0.2);
    
    &::before {
      content: '';
      position: absolute;
      right: -8rpx;
      top: 20rpx;
      width: 0;
      height: 0;
      border-top: 8rpx solid transparent;
      border-bottom: 8rpx solid transparent;
      border-left: 8rpx solid #4D7CBF;
    }
  }

  .message-text {
    font-size: 30rpx;
    line-height: 1.5;
    color: inherit;
  }
  
  .message-image {
    max-width: 400rpx;
    max-height: 400rpx;
    border-radius: 12rpx;
    display: block;
    margin-bottom: 10rpx;
  }
  
  .message-location {
    display: flex;
    align-items: center;
    padding: 20rpx;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 12rpx;
    margin-bottom: 10rpx;
    min-width: 200rpx;
    max-width: 300rpx;
  }
  
  .location-icon {
    font-size: 32rpx;
    margin-right: 15rpx;
  }
  
  .location-content {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  
  .location-name {
    font-size: 28rpx;
    font-weight: bold;
    margin-bottom: 5rpx;
    color: inherit;
  }
  
  .location-address {
    font-size: 24rpx;
    line-height: 1.3;
    opacity: 0.8;
    color: inherit;
  }
  
  .message-meta {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 10rpx;
    padding: 0 6rpx;
  }
  
  .sender-name {
    font-size: 20rpx;
    color: #86909C;
    font-weight: 500;
    margin-top: 8rpx;
    text-align: center;
    max-width: 80rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .message-time {
    font-size: 22rpx;
    color: #86909C;
    font-weight: 400;
  }
  
  .message-status {
    display: flex;
    align-items: center;
    margin-left: 8rpx;
  }
  
  .recalled-text {
    font-size: 20rpx;
    color: rgba(255, 255, 255, 0.6);
    font-style: italic;
  }
}

.search-bar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 20rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
}

.search-input-container {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 25rpx;
  padding: 15rpx 20rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.search-input {
  flex: 1;
  margin: 0 15rpx;
  font-size: 28rpx;
  color: #333;
}

.chat-input-area {
  height: 120rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-top: 1rpx solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .input-left {
    display: flex;
    align-items: center;
    margin-right: 20rpx;
    
    uni-icons {
      margin-right: 25rpx;
      padding: 10rpx;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.5);
      transition: all 0.3s ease;
      
      &:active {
        background: rgba(255, 255, 255, 0.8);
        transform: scale(0.95);
      }
    }
  }
  
  .input-center {
    flex: 1;
    
    .input-text {
      height: 80rpx;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 40rpx;
      padding: 0 30rpx;
      font-size: 30rpx;
      border: 1rpx solid rgba(77, 124, 191, 0.15);
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
      color: #1D2129;
      
      &::placeholder {
        color: #86909C;
      }
    }
  }
  
  .input-right {
    margin-left: 20rpx;
    
    .send-button {
      height: 80rpx;
      min-width: 120rpx;
      line-height: 80rpx;
      background: linear-gradient(135deg, #4D7CBF 0%, #3A5F95 100%);
      color: #fff;
      border-radius: 40rpx;
      font-size: 30rpx;
      padding: 0 30rpx;
      box-shadow: 0 2rpx 8rpx rgba(77, 124, 191, 0.2);
      transition: all 0.2s ease;
      
      &[disabled] {
        background: #C9CDD4;
        color: #86909C;
        box-shadow: none;
      }
      
      &:active:not([disabled]) {
        transform: scale(0.95);
        box-shadow: 0 1rpx 4rpx rgba(77, 124, 191, 0.3);
      }
    }
    
    .card-button {
      height: 80rpx;
      line-height: 80rpx;
      background: linear-gradient(135deg, #2196F3 0%, #21CBF3 100%);
      color: #fff;
      border-radius: 40rpx;
      font-size: 28rpx;
      padding: 0 25rpx;
      box-shadow: 0 4rpx 15rpx rgba(33, 150, 243, 0.3);
    }
  }
}

.task-menu {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 30rpx 30rpx 0 0;
  padding: 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .menu-item {
    display: flex;
    align-items: center;
    padding: 25rpx 0;
    border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    
    &:last-child {
      border-bottom: none;
    }
    
    &:active {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 15rpx;
    }
    
    uni-icons {
      margin-right: 20rpx;
      padding: 8rpx;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.05);
    }
    
    text {
      font-size: 30rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.rotating {
  animation: rotating 1s linear infinite;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>